import axios, {type Method} from 'axios'
// import {instances} from "element-plus/es/components/message/src/instance";
import {getToken, removeToken} from "@/utils/auth";
// import {useUserStore} from "@/stores/user";
import router from "@/router";
import {ElMessage} from "element-plus";

const service = axios.create({
    baseURL: 'https://api-hmzs.itheima.net/tj',
    timeout: 5000,
})

service.interceptors.request.use(
    config => {
        const token = getToken()
        if (token) {
            config.headers.Authorization = 'Bearer ' + token;
        }
        return config
    },
    error => {
        return Promise.reject(error)
    },
)

service.interceptors.response.use(
    response => {
        return response.data
    },
    error => {
        if (error.response) {
            if (error.response.status === 401) {
                // 认证失败，可以在这里处理重新登录的逻辑
                // const store = useUserStore();
                // store.removeToken();
                removeToken();
                // 跳转登录页
                router.push("/login");
                ElMessage.error("认证失败，请重新登录");
            } else if (error.response.status === 400) {
                // 参数错误，后端有提示信息
                ElMessage.error(error.response.data.msg);
            } else {
                // 未知错误，如果后端有提示信息就显示，否则显示未知错误
                ElMessage.error(error.response.data?.msg || "未知网络错误");
            }
        } else {
            if (error.message.includes("timeout")) {
                ElMessage.error("网络请求超时");
            } else {
                ElMessage.error("请检查网络状态");
            }
        }
        return Promise.reject(error)
    },
)
const request = <T>(url: string, method: Method = "GET", submitData?: object) => {
    return service.request({
        url,
        method,
        [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData
    })
}

export interface ServiceResponse<T> {
    code: number
    data: T
    msg: string
}

export default service
export {request};